#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xlrd
from flask_login import login_required
from werkzeug.datastructures import CombinedMultiDict
from my_app import db
from my_app.cash_value.depend import query_policy_content, cash_value_run
from my_app.cash_value.models import DataBaseConfig, DataBaseConfigForm
from my_app.auth.models import User
from my_app.auth.views import current_user
from flask import flash, redirect, url_for, render_template, request, Blueprint, abort, jsonify

cash_value = Blueprint("cash_value", __name__)


@cash_value.route("/database/<id>")
@login_required
def database_info(id):
    """数据库配置信息页"""
    database = DataBaseConfig.query.get_or_404(id)
    return render_template("cash_value/database.html", database=database)


@cash_value.route("/databases")
@cash_value.route("/databases/<int:page>")
@login_required
def databases_list(page=1):
    """数据库配置列表"""
    databases = DataBaseConfig.query.filter().order_by(DataBaseConfig.id.desc()).paginate(page, 10)
    return render_template("cash_value/databases.html", databases=databases)


@cash_value.route("/database-create", methods=["POST", "GET"])
@login_required
def create_database():
    """新增数据库配置信息"""
    form = DataBaseConfigForm(CombinedMultiDict([request.form]))
    if form.validate_on_submit():
        user_id = User.query.get_or_404(current_user.id)
        env = form.env.data
        host = form.host.data
        port = form.port.data
        username = form.username.data
        password = form.password.data
        database = form.database.data
        api_path = form.api_path.data
        database_config = DataBaseConfig(env, host, port, username, password, database, api_path, user_id)
        db.session.add(database_config)
        db.session.commit()
        flash(f"{env} 环境数据库配置信息创建成功.")
        return redirect(url_for('cash_value.database_info', id=database_config.id))
    if form.errors:
        flash(form.errors, 'danger')
    return render_template('cash_value/database-create.html', form=form)


@cash_value.route("/database-update/<id>", methods=["GET", "POST"])
@login_required
def update_database(id):
    """编辑数据库配置信息"""
    database = DataBaseConfig.query.get_or_404(id)
    form = DataBaseConfigForm(CombinedMultiDict([request.form]), obj=database)
    if form.validate_on_submit():
        database.env = form.env.data
        database.host = form.host.data
        database.port = form.port.data
        database.username = form.username.data
        database.password = form.password.data
        database.database = form.database.data
        database.api_path = form.api_path.data
        db.session.add(database)
        db.session.commit()
        flash(f"{database.env} 环境数据库配置信息编辑成功.")
        return redirect(url_for('cash_value.database_info', id=database.id))
    if form.errors:
        flash(form.errors, 'danger')
    return render_template('cash_value/database-update.html', form=form, database=database)


@cash_value.route("/database-delete/<id>")
@login_required
def delete_database(id):
    """删除数据库配置信息"""
    database = DataBaseConfig.query.get_or_404(id)
    db.session.delete(database)
    db.session.commit()
    return redirect(url_for('cash_value.databases_list'))


@cash_value.route("/ajax-cash-value", methods=['POST', 'GET'])
def cash_value_ajax():
    """将基础数据渲染至页面"""
    configs = [e for e in DataBaseConfig.query.all()]
    return render_template("cash_value/ajax-query.html", configs=configs)


@cash_value.route("/policy-info", methods=['POST', 'GET'])
def query_policy_info():
    """保单信息"""
    policy_num = request.form.get("policy_num")
    env_id = request.form.get("env_id")
    if request.method == "POST":
        db_config = DataBaseConfig.query.get_or_404(env_id)
        db_dict = {
            "env": db_config.env, "host": db_config.host, "port": db_config.port,
            "username": db_config.username, "password": db_config.password,
            "database": db_config.database, "api_path": db_config.api_path
        }
        _policy_info = query_policy_content(db_config=db_dict, policy_id=policy_num)

        if _policy_info is None:
            return jsonify({"status": 201, "message": "没有查询到任何保单数据，请确保环境以及保单号正确"})
        if _policy_info == "JSONDecodeError":
            return jsonify({"status": 202, "message": "查询保单数据异常，原因：JSONDecodeError"})
        else:
            _policy_info.append(db_dict['api_path'])
            return jsonify({"status": 200, "message": _policy_info})


@login_required
@cash_value.route("/execute-cash-value", methods=['POST', 'GET'])
def cash_value_execute():
    """执行现价"""
    file = request.files.get('file_input')  # 文件
    env_name = request.form.get("env_name")  # 环境名称
    p_uuid = request.form.get("p_uuid")  # 保单UUID
    p_premium = request.form.get("p_premium")  # 保费
    p_amount = request.form.get("p_amount")  # 保额
    api_path = request.form.get("api_path")  # 请求地址
    formula_mode = request.form.get("formula_mode")  # 计算方式
    policy_year = request.form.get("policy_year")  # 最大年度
    base_money = request.form.get("base_money")  # 基础额度
    if request.method == "POST":
        if file:
            f = file.read()
            try:
                work_book = xlrd.open_workbook(file_contents=f)  # 接收二进制的文件内容
                sheet_name = work_book.sheet_by_index(0)
            except xlrd.biffh.XLRDError as e:
                return jsonify({"status": 201, "message": f"错误的源文件：{e} ；请确保文件的格式为xls！"})
            except BaseException as e:
                return jsonify({"status": 202, "message": f"打开文件时触发了一个广泛异常：{e}"})
            else:
                base_cash = []
                for col in range(sheet_name.ncols):
                    col_values = sheet_name.col_values(col)
                    for value in col_values:  # 文件中的基础现价
                        if value != '':
                            base_cash.append(value)
                money = p_premium if formula_mode == "保费" else p_amount
                money = float(money)
                base_money = int(base_money)
                policy_year = int(policy_year)
                run_mess = cash_value_run(
                    base_cash=base_cash, base_money=base_money, money=money,
                    api_path=api_path, policy_uuid=p_uuid, policy_year=policy_year, env=env_name
                )
                print(jsonify({"status": 200, "message": run_mess}).json)
                return jsonify({"status": 200, "message": run_mess})
        # 没有获取到文件
        return jsonify({"status": 204, "message": "文件可能无值，请更换文件试试~"})
    # 非post请求
    return abort(405, "方法不允许")



